<template>
  <a-card title="📋 所有预定" class="booking-list-card">
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <a-row :gutter="[8, 8]">
        <a-col :xs="24" :sm="8">
          <a-date-picker
            v-model:value="filters.date"
            placeholder="按日期筛选"
            style="width: 100%"
            @change="fetchBookings"
          />
        </a-col>
        <a-col :xs="24" :sm="8">
          <a-select
            v-model:value="filters.room_id"
            placeholder="所有会议室"
            style="width: 100%"
            allow-clear
            @change="fetchBookings"
          >
            <a-select-option
              v-for="room in rooms"
              :key="room.id"
              :value="room.id"
            >
              {{ room.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="8">
          <a-input
            v-model:value="filters.booking_person"
            placeholder="按预定人搜索"
            allow-clear
            @pressEnter="fetchBookings"
          >
            <template #suffix>
              <SearchOutlined @click="fetchBookings" style="cursor: pointer" />
            </template>
          </a-input>
        </a-col>
      </a-row>
    </div>

    <!-- 预定列表 -->
    <a-spin :spinning="loading">
      <div class="bookings-container">
        <div v-if="bookings.length === 0" class="empty-state">
          <a-empty description="暂无预定记录" />
        </div>
        
        <div
          v-for="booking in bookings"
          :key="booking.id"
          class="booking-item"
          :class="`status-${booking.status}`"
        >
          <div class="booking-header">
            <span class="room-name">{{ booking.room_name }}</span>
            <a-tag :color="getStatusColor(booking.status)">
              {{ booking.status.toUpperCase() }}
            </a-tag>
          </div>

          <a-row :gutter="[8, 8]" class="booking-details">
            <a-col :span="12">
              <strong>日期:</strong> {{ formatDate(booking.start_time) }}
            </a-col>
            <a-col :span="12">
              <strong>时间:</strong> {{ formatTime(booking.start_time) }} - {{ formatTime(booking.end_time) }}
            </a-col>
            <a-col :span="12">
              <strong>预定人:</strong> {{ booking.booking_person }}
            </a-col>
            <a-col :span="12">
              <strong>时长:</strong> {{ calculateDuration(booking.start_time, booking.end_time) }}
            </a-col>
          </a-row>

          <div class="booking-content">
            <strong>会议:</strong> {{ booking.meeting_content }}
          </div>

          <!-- 取消预定按钮已被屏蔽 -->
          <!--
          <div class="booking-actions" v-if="booking.status !== 'cancelled'">
            <a-button
              type="link"
              danger
              size="small"
              @click="handleCancelBooking(booking.id)"
            >
              取消
            </a-button>
          </div>
          -->
        </div>
      </div>
    </a-spin>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <a-button @click="loadMore" :loading="loading" block>
        加载更多
      </a-button>
    </div>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { getBookings, deleteBooking } from '@/services/bookingService'
import { getRooms } from '@/services/roomService'

const loading = ref(false)
const bookings = ref([])
const rooms = ref([])
const hasMore = ref(false)
const currentPage = ref(0)
const pageSize = 20

const filters = reactive({
  date: null,
  room_id: undefined,
  booking_person: '',
})

const fetchBookings = async (append = false) => {
  loading.value = true
  try {
    const params = {
      skip: append ? currentPage.value * pageSize : 0,
      limit: pageSize,
    }

    if (filters.date) {
      params.date = filters.date.toISOString()
    }
    if (filters.room_id) {
      params.room_id = filters.room_id
    }
    if (filters.booking_person) {
      params.booking_person = filters.booking_person
    }

    // 只获取有效的预定（不包括已取消的）
    params.status = 'CONFIRMED'

    const data = await getBookings(params)
    
    // 只显示有效的预定，过滤掉已取消的预定
    const validBookings = data.filter(booking => booking.status !== 'CANCELLED')
    
    if (append) {
      bookings.value = [...bookings.value, ...validBookings]
    } else {
      bookings.value = validBookings
      currentPage.value = 0
    }

    hasMore.value = validBookings.length === pageSize
    if (append) {
      currentPage.value++
    }
  } catch (error) {
    message.error('加载预定列表失败')
  } finally {
    loading.value = false
  }
}

const loadMore = () => {
  currentPage.value++
  fetchBookings(true)
}

const fetchRooms = async () => {
  try {
    rooms.value = await getRooms()
  } catch (error) {
    message.error('加载会议室列表失败')
  }
}

// 屏蔽取消预定功能
/*
const handleCancelBooking = (bookingId) => {
  Modal.confirm({
    title: '取消预定',
    content: '确定要取消这个预定吗？',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteBooking(bookingId)
        message.success('预定已取消')
        fetchBookings()
      } catch (error) {
        message.error('取消预定失败')
      }
    },
  })
}
*/

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD')
}

const formatTime = (dateString) => {
  return dayjs(dateString).format('HH:mm')
}

const calculateDuration = (startTime, endTime) => {
  const start = dayjs(startTime)
  const end = dayjs(endTime)
  const hours = end.diff(start, 'hour')
  const minutes = end.diff(start, 'minute') % 60
  
  if (hours > 0 && minutes > 0) {
    return `${hours}h ${minutes}m`
  } else if (hours > 0) {
    return `${hours}h`
  } else {
    return `${minutes}m`
  }
}

const getStatusColor = (status) => {
  const colors = {
    pending: 'orange',
    confirmed: 'blue',
    ongoing: 'green',
    completed: 'default',
    cancelled: 'red',
  }
  return colors[status] || 'default'
}

onMounted(() => {
  fetchBookings()
  fetchRooms()
})

// Expose fetchBookings for parent component
defineExpose({
  fetchBookings,
})
</script>

<style scoped>
.booking-list-card {
  height: 100%;
}

.filter-bar {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 4px;
}

.bookings-container {
  max-height: 600px;
  overflow-y: auto;
}

.booking-item {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
  background: #fafafa;
  transition: all 0.3s;
}

.booking-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.booking-item.status-cancelled {
  opacity: 0.6;
}

.booking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.room-name {
  font-weight: 600;
  color: #1890ff;
  font-size: 16px;
}

.booking-details {
  font-size: 14px;
  color: #595959;
  margin-bottom: 12px;
}

.booking-content {
  padding-top: 12px;
  border-top: 1px solid #e8e8e8;
  font-size: 14px;
  color: #595959;
}

.booking-actions {
  margin-top: 8px;
  text-align: right;
}

.empty-state {
  padding: 40px 0;
}

.load-more {
  margin-top: 16px;
}
</style>